Skip to content

feat(server): sweep the objects that no row names - #526

Merged
pdevito3 merged 8 commits into
mainfrom
feat/orphan-object-sweeper
Nov 15, 2026
Merged

pdevito3 merged 8 commits into
mainfrom
feat/orphan-object-sweeper

Conversation

@pdevito3

Copy link
Copy Markdown
Owner

Why

Each non-terminal state of an attachment needs a sure way out, also after a crash. Two faults had none:

  • F1. An object stayed in the bucket with no row and no job, and no code deleted it. The process dies between the put and the save, the cleanup of a failed add fails, or a put that the client stopped lands under a tenant after its DeleteTenantObjects job listed the prefix.
  • F2 (found in the model). The save throws while its COMMIT is still in flight. The cleanup at once checks for the row on a new connection, sees none, and deletes the object. Then the COMMIT lands, and the list shows a file that no one can download.

What changed

  • The sweep of the bucket. SweepObjects is a recurring BackWave system job on its own queue object-sweep, in Domain/ObjectDeletes/. Each run lists the objects under tenants/, one page of 1000 keys at a time. It deletes an object only when all of these are true:
    • It is older than the grace, Attachments:AddTimeout (5 min) plus ObjectStorage:Sweep:Margin (1 h).
    • Its key names a tenant of this database. A deleted tenant counts.
    • No live row names it in a StoredFile column.
  • The decision is a pure function. ObjectSweep.VerdictOf and ObjectSweep.Decide make the decision, with unit tests. The handler only lists, queries, and deletes.
  • The storage key columns come from the EF model. StoredFileMapping.StorageKeyColumns finds each StoredFile column there, also on a derived entity type and inside another value object, so a new stored file needs no change to the sweep. A collection of stored files, or a stored file in one column, stops the sweep, because it cannot read their keys. A soft-deleted row does not name its key.
  • The fences.
    • The sweep keeps an object whose key names no tenant of the database, and logs a Warning with the count.
    • It skips the whole run while the database has a migration that this Server does not know, for example while an older Server runs during a deploy or after a rollback.
  • The add has a time limit. Attachments:AddTimeout stops the put and the save, also when the caller does not cancel. So the grace is a real bound. A migration indexes storage_key, and StorageKeyIndexTests fails for a storage key column with no such index.
  • No cleanup at once. AttachmentStorage.AddAsync keeps the object when the put or the save throws. The sweep deletes it after the grace, when a COMMIT in flight has landed or failed. This removes the cleanup that fix(server): delete the object of an attachment whose put throws in AttachmentStorage.AddAsync #519 extended.
  • The S3 client keeps the clock of the Server. ObjectStorageRegistration turns off the clock skew correction of the SDK. With it on, the SDK signs with the clock of S3 after one refusal, so the 15-minute rule of S3 did not bound the clock that the sweep reads. Now S3 refuses each call of a Server whose clock is more than 15 minutes off. ObjectStorageClockTests checks this against a fake S3 whose clock is 20 minutes ahead.
  • System jobs. ISystemJob and SystemJobHandler run a job as the caller System. JobScope gives it the same telemetry and unsaved-work check as a tenant job.
  • The model. The skill object-storage-lifecycle (TLA+) models the sweep. Its coverage record maps each sweep action to its code, at the sync commit c5abb78b.

Scope

  • Run interval. Daily at 03:00 UTC (ObjectStorage:Sweep:Schedule, cron). The schedule uses Coalesce, so missed ticks give one run, and noOverlap is on. Each start of the Server defines the schedule after the migrations.
  • Cost of the list. Each run lists the whole bucket under tenants/. That is one LIST request for each 1000 objects. Each page also runs one query on tenants and one indexed query on each storage key column, plus one DeleteObjects call when the page has orphans. At 1 million objects, a run is about 1000 LIST requests.
  • The longest life of an orphan. It stays until the first daily run after its grace, at most about 25 hours.
  • Not in scope. No intent row before the put. No sweep of other prefixes. No alert on a skipped sweep beyond its Warning log.

Tradeoffs

Blast Radius

  • Every object under tenants/ must be the StoredFile of a row. An app that keeps other files under tenants/ loses them on the first run after the grace. template-updates.md says to move such files first.
  • A Server whose clock is more than 15 minutes off now fails each call to storage. Before, the SDK took the clock of S3 and the call worked. The tokens already need synced clocks (DPoP allows 5 s of skew). template-updates.md says to keep each host on NTP.
  • The IAM needs s3:ListBucket. The credentials of each process that runs jobs need it. They already need it for a tenant delete.
  • The logs of the removed cleanup are gone. These are Kept the object of attachment, Could not delete the object of unsaved attachment, and The save of attachment ... failed after its commit.
  • A new queue and a new schedule row. The queue is object-sweep, with a default worker group. The schedule row is sweep-objects in the backwave schema. The jobs dashboard still refuses a manual trigger of a schedule.
  • AttachmentStorage.AddAsync gives the save a token. Each app attachment add must pass addToken to RunSharedAsync, and the build fails until it does (template-updates.md).

Verification

  • Build. dotnet build FullstackTemplate.slnx gives 0 warnings and 0 errors.
  • Unit tests. 2424 of 2424 pass, with the sweep decision, the scan of the storage key columns, the options, and the doc links.
  • Integration tests. 567 of 567 pass, on real Postgres and Floci.
  • Functional tests. ServerRoleTests 6/6, JobsDashboardTests 7/7, and WorkshopAttachmentTests 16/16 pass.
  • Live stack. On an isolated Aspire stack, backwave.schedules has sweep-objects with 0 0 3 * * *, a catch-up of 1, and no overlap. A sweep that I enqueued through CSharpRepl logged Swept the bucket: listed 2 objects, kept 2, and deleted 0. Its span has app.caller.kind=system and the three count tags, and its query on tenants has no soft-delete filter.
  • Fail before. I broke the code one way at a time, and each break failed the test that it should:
    • The sweep does nothing: all 6 SweepObjectsTests and both WorkshopAttachmentSweepTests fail.
    • No age check: the younger-object test fails.
    • No row check: the live-attachment test fails.
    • No caller scope: the live-attachment test fails.
    • Soft-deleted rows name their keys: the deleted-attachment test fails.
    • No tenant fence: the unknown-tenant test fails.
    • Live tenants only: the late-put-under-a-deleted-tenant test fails.
    • No migration fence: the fence test fails.
    • <= changed to < at the grace: the boundary unit test fails.
    • The converted lost-reply test fails with the old cleanup (the object is gone at once) and with no sweep (the object stays).
    • The scan with the old filter (root IAttachment types, File only): both StorageKeyColumnsTests of the scan fail.
    • No guard for a stored file in one column: the one-column test fails.
    • Skew correction on: ObjectStorageClockTests fails, because the SDK takes the clock of the fake S3 and the list works.
  • Model. check.sh has all 8 configs at baseline.
    • Before the sweep: ObjectStorage, Liveness, and Chart passed. Configs with orphans broke EveryObjectAccounted and NoObjectLeftInDeletedTenant. LateCommit broke NoLiveRowWithoutObject (F2).
    • After: ObjectStorage (904,176 states), Liveness, and Chart pass with late commits on. DeletedTenantOrphan shows that OrphansGo holds. GraceNone, GraceLimit, and SoftDeletedNames show the harm of each other choice.

@pdevito3

Copy link
Copy Markdown
Owner Author

Review findings that stay open

The review gate (one review and one re-review) found these. Each fixed finding is in the commits. Each open finding has its reason here.

Fixed

  • M1. The sweep read only IAttachment.File on root entity types, so it deleted a live file kept in any other StoredFile. Now StoredFileMapping.StorageKeyColumns gives each StoredFile column of the model, also on a derived entity type and inside another value object. A collection of stored files stops the sweep. StorageKeyColumnsTests fails with the old filter, and StorageKeyIndexTests now checks each of these columns.

  • L5. attachments.md did not say that a COMMIT that stays in flight past the margin can land after the sweep deleted its object. The Limits section says it now.

  • L4, doc half. attachments.md now says to give each process the same Attachments:AddTimeout, because the process that runs the sweep takes the grace from its own settings.

  • Re-review, medium. StorageKeyIndexTests asserted that the model has a storage key column. An app with no stored file, for example after scripts/remove-examples.cs, failed it. The assert is gone, and the test now checks each column that the model has.

  • Re-review, low. A StoredFile kept in one column with a value converter hid its key from the scan, so the sweep could delete its object. Now the scan stops with NotSupportedException, and a_stored_file_in_one_column_stops_the_scan fails without the guard.

  • Re-review, low. attachments.md said that each deleted row gets a delete job. Only the File of an IAttachment gets one. The doc now says that the sweep deletes the object of any other StoredFile after the grace.

  • Re-review, low. Two summaries and the Warning log of the tenant fence used words from before M1. They now name the storage key columns.

  • Re-review, low. The scan test did not cover two stored files on one entity. Brand.Banner covers it now.

Open

  • M2. A copy of the database that uses the same bucket deletes the objects of the rows that the copy does not have. The proposed guard is a marker object that holds a database ID. A snapshot restore copies that ID into staging, and also the Postgres system identifier, so the marker cannot tell production from its copy. A sound fence needs an identity that each deploy has and that the data does not carry. That is a product decision. The rule is in backend.md, attachments.md, and template-updates.md.
  • L1. One key that storage refuses to delete stops the run at its page. The run fails, BackWave runs it again with backoff, and the next daily run starts again. So the fault is loud (a failed job and an Error log), not silent. Such a key (Object Lock, a deny policy) also breaks the delete jobs and the tenant delete. A run that goes on past failed keys changes the retry contract of the job, so it is a follow-up.
  • L2. The migration fence runs once for each run. A check for each page makes the window smaller but does not close it. A sound fix needs a lock that the migration also takes. The harm needs a migration that moves attachment rows into a table that the old Server does not know, while a run of the old Server is in progress.
  • L3. Nothing stops a put under tenants/ outside AttachmentStorage.AddAsync. A ban of ObjectStorage.PutAsync also stops each put outside tenants/, and the sweep does not touch those puts. The rule is in attachments.md. An add that ignores addToken still compiles. template-updates.md says to pass it.
  • L4, bound half. Attachments:AddTimeout has no upper bound. A value over about 49.7 days makes CancelAfter throw at each add.
  • L6. A tenant delete now needs LastModified in each listed object. ListObjectsV2 of S3 gives it for each object, and the error names the store and the key.
  • L7. The Warning about unknown tenants also counts keys that name no tenant at all, such as tenants/not-a-tenant/x. Its text is true for them ("name no tenant of this database"). Only its hint about another database can mislead.
  • L8. Floci refuses a request that is signed more than 15 minutes off. I checked this. A request to the test Floci signed now gets 200, and requests signed 20 minutes behind or ahead get 403 RequestTimeTooSkewed. The S3 client no longer corrects the clock, so in a local run a Docker VM clock that drifts past 15 minutes (for example after a sleep) fails each call to storage until Docker syncs it. The failure is loud and loses no data. An exception for the endpoint path would also exempt S3-compatible stores in production, where the bound matters.
  • The sync commit of the model. object-storage-lifecycle/SKILL.md names c5abb78b, a commit of this branch. After a squash merge, set it to the merge commit.
  • Re-review. A new app query filter would hide live rows from the sweep. The loaders keep each query filter, so that a soft-deleted row names no key and the tenant filter scopes the system caller. A third named filter, for example an archive filter, would hide its rows, and the sweep would delete their objects after the grace. Today only SoftDelete and Tenant exist, so this is latent. The fix (ignore each filter and apply the soft-delete rule in the loader, or a test that fails on an unknown filter name) changes the filter rules of the app, so I left it to the owner of those rules.
  • Re-review. A StoredFile mapped to JSON cannot pass StorageKeyIndexTests. Postgres cannot put a plain index on a key inside a JSON column, so that test fails for it. The failure is loud and loses no data. The template has no such mapping, and the right index (an expression index or a GIN index) depends on the app.
  • Re-review. No unit test reads the SQL of each loader with ToQueryString. SweepObjectsTests and WorkshopAttachmentSweepTests run the loaders on real Postgres, and they fail with no row check or no caller scope. A SQL text test would pin the implementation, not the behavior.

@pdevito3

Copy link
Copy Markdown
Owner Author

Maintainer decision on M2: keep the documented rule (each database gets its own bucket, as backend.md, attachments.md, and template-updates.md state). No code fence in this PR.

Base automatically changed from fix/object-storage-exits to main November 15, 2026 18:12
pdevito3 added a commit that referenced this pull request Nov 15, 2026
#527)

## Why

A hung Server or a dropped network kept the SPA pending with no end. An
upload had no cancel. Now each request has a time limit at the BFF and
in the SPA, and the user can cancel an upload.

## What changed

- The BFF forwarder has a 30 s idle limit, and a multipart upload has 5
min (`Bff:Proxy` options, one row per content type). A request that
reaches its limit gets a 504.
- The SPA API client stops a request after 35 s, or 10 min for an
upload. A 504 or a timeout shows one message: "The server did not answer
in time. Reload the page to see the latest data, then try again."
- During an upload, the Files section shows a "Cancel upload" button. It
stops the request, goes back to idle, moves the focus to the upload
button, and shows no toast.

## Scope

- Covers every proxied API call and the attachment upload.
- Does not add retries or a dedupe of uploads.

## Tradeoffs

- No dedupe. If the Server already saved a file when the user cancels,
the file stays, and a second upload adds a copy. The Limits section of
the attachments doc says so. A dedupe key costs more than a rare
duplicate that the user can delete.
- The upload limit is a BFF option and not the Server's
`Attachments:AddTimeout`, because main has no such setting. When #526
lands, set the BFF value from it.
- The SPA limits count the total time, so they are a little longer than
the BFF idle limits. The 504 of the BFF comes first, and the SPA limit
stops the wait only when the BFF itself does not answer.

## Blast Radius

The change touches all proxied API calls. A Server call that sends no
bytes for 30 s now fails with a 504. The Server has no streaming or
long-poll endpoint today.

## Verification

- Before the fix, the new BFF, Playwright claim, and cancel tests
failed. After it, they pass, and each new Playwright test passed 10 of
10 runs with `--repeat-each=10`.
- The tests of a hung request set a short limit, so they do not wait for
the real ones. The BFF test sets `Bff:Proxy:ActivityTimeout` to 1 s (30
s before, now 1.8 s). The Playwright claim test cuts the browser limit
of the claim request to 1 s with `shortenRequestTimeLimit` (36.1 s
before, now 1.5 to 2.5 s). The browser counts the XHR limit, so
`page.clock` cannot reach it. A BFF test and the SPA unit test pin the
defaults: 30 s, 5 min, 35 s, and 10 min. With the limit code removed,
each shortened test fails.
- The solution builds with 0 warnings. 516 BFF tests pass, and `pnpm
lint`, `pnpm build`, `pnpm test` (874 tests), `join.spec.ts` with
`--repeat-each=10` (540 of 540), and `pnpm test:e2e` (360 tests) pass.
- On the live stack, a throttled real upload stopped when the user
pressed Cancel upload, with no toast. Light, dark, and narrow
screenshots look correct.
…deletes

The model comes from fv/object-storage and now describes the code at 80d9f8f. The jobs of the
object-deletes queue replace the request runner: an outcome is fenced on the lease, and an expired
lease counts as an attempt. The put is inside the try, and a canceled save runs the cleanup.

F1 (an object with no row that no code deletes) and F2 (a late COMMIT whose object the cleanup
deletes) still show.
The model adds a recurring sweep: it lists the bucket, keeps the keys older than the grace, reads
the live rows, and deletes the rest. OrphansGo proves under fairness of the sweep that each object
with no live row goes, also the object that lands under a deleted tenant after its prefix delete.

The configs show the decisions of the code that follows. The grace needs the time limit of an add
and a margin for a COMMIT in flight (GraceNone, GraceLimit). A soft-deleted row must not keep its
object (SoftDeletedNames). The cleanup at once of a failed add is the cause of F2 (LateCommit), and
with it gone the safety gate passes with late commits on.
The sweep of the bucket looks up each page of keys in each attachment
table. EF Core 10 cannot index a column of a value object, so the
migration adds the index. AttachmentStorageKeyIndexTests fails on an
attachment table with no index on storage_key.
The put and the save of an add had no time limit of their own. An add
whose caller waited on could run for any time, so no age of an object
in the bucket proved that its add had ended. The add now stops its put
and its save after Attachments:AddTimeout (5 minutes) and throws a
TimeoutException. The save of the row gets the token of the limit, and
gives it to the tenant lock.
An add that stops between its put and its save leaves an object with no
row, and so does a put that lands after the delete of the objects of its
tenant. No code deleted these objects.

SweepObjects is a recurring system job on the queue object-sweep. It
runs each day at 03:00 UTC, lists the bucket under tenants/ one page at
a time, and deletes each object that is older than AddTimeout plus a
margin, whose tenant is a tenant of the database, and that no live row
names in a StoredFile column. StoredFileMapping.StorageKeyColumns finds
these columns in the EF model, also on a derived entity type and inside
another value object, and refuses a stored file that it cannot read. A
soft-deleted row does not name its key. StorageKeyIndexTests, the old
AttachmentStorageKeyIndexTests, checks the index of each such column.

The sweep does not run while the database has a migration that the
Server does not know, so an older Server does not delete the objects of
a newer storage key column. ObjectSweep holds the decision as a pure
function, and the handler only reads and deletes.

The S3 client no longer corrects its clock to the clock of S3. S3 then
refuses each call of a Server whose clock is more than 15 minutes off,
and the grace of the sweep needs that bound.
A save can throw while its COMMIT is still in flight. The cleanup of the
failed add then checked for the row on a new connection, saw none, and
deleted the object, and the COMMIT landed: the list showed a file that
no one could download (F2 in the object storage model).

The add now keeps the object when the put or the save throws. The sweep
of the bucket deletes it after the grace, when a COMMIT in flight has
landed or failed. The test of a lost put reply now shows that the object
stays after the add and that the sweep deletes it.
The coverage record now maps Age, SweepList, SweepCheck, SweepDelete,
and SweepFail to SweepObjects, ObjectSweep, NamedStorageKeys, and
ObjectSweepSchedule. The sync commit moves to 83bdc7ae, where the model
with Cleanup = FALSE describes the code. check.sh stays at its baseline.
… model

The model is core, so an app with no examples keeps it. CheckWorkshop is now
CheckOwner, the comments name the add and delete handler of an attachment, and
the lines of SKILL.md that name the workshop handlers or their tests are in
example sections. The model semantics are the same.
@pdevito3
pdevito3 force-pushed the feat/orphan-object-sweeper branch from ff2ed66 to 157c4ea Compare November 15, 2026 18:19
@pdevito3
pdevito3 merged commit d4c3fef into main Nov 15, 2026
23 checks passed
@pdevito3
pdevito3 deleted the feat/orphan-object-sweeper branch November 15, 2026 18:43
pdevito3 added a commit that referenced this pull request Nov 16, 2026
…sh commits on main (#533)

## Why

The formal verification skills must stay true to the code on main. The
three TLA+ skills recorded sync commits from their PR branches. A squash
merge left those commits off main, so the `git log <sync>..HEAD` check
in each skill named a commit that main does not have.

## What changed

- `bff-session-lifecycle` now syncs to `a1637f8a` (#525).
`object-storage-lifecycle` syncs to `d4c3fef7` (#526).
`membership-lifecycle` syncs to `adeb4db0` (#528).
- The skills cited other branch commits as history. Each of those now
names the main commit that holds the same code, which is #519 or #521.

## Scope

- No change to a model, a config, or `check.sh`. The covered code that
main changed after each branch point does not change what the models
describe.
- No product code changes.

## Blast Radius

Only skill text changes, so the app is not affected. An agent that uses
these skills now compares against commits that exist on main.

## Verification

- `bff-session-lifecycle/model/check.sh` printed only `ok` lines.
`object-storage-lifecycle/check.sh` kept every config at its baseline.
`membership-lifecycle/check.sh` passed all 4 configs.
- `scripts/remove-examples.cs` and the example-name grep of
`without-examples.cs` passed on a copy of this branch. The full script
stopped at its Docker check because Docker Desktop did not start.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant